<?php
/**
 * Create by 11li
 * Date 2020/4/2
 * Time 21:21
 *
 */

namespace app\common\service\v2;


use app\admin\model\User;
use app\common\model\AgentShop;
use app\common\model\Promotion;

class UserService
{
	
	/**
	 * 获取一个用户的发展中心的ID
	 * @param $userId
	 * @return string
	 * @throws \think\exception\DbException
	 */
	public static function getUserCenterUserId($userId){
		
		$agentId = '';
		$user = User::get($userId);
		if(!$user) {
			return '';
		}
		if($user['level'] == User::LEVEL_CENTER) {
			return $userId;
		}
		
		if($user['level'] == User::LEVEL_PROMOTION) {
			$promoter = Promotion::get(['user_id' => $userId]);
			if(!$promoter) {
				return '';
			}
			
			if($promoter['agent_shop_id']) {
				$agent = AgentShop::get($promoter['agent_shop_id']);
				if($agent['role'] == User::LEVEL_CENTER) {
					return $agent['user_id'];
				} else {
					$agentId = $agent['center_id'];
				}
			}
		} else if($user['level'] != User::LEVEL_USER) {
			$agent = AgentShop::get(['user_id' => $user['id']]);
			if($agent['role'] == User::LEVEL_CENTER) {
				return $agent['user_id'];
			} else {
				$agentId = $agent['center_id'];
			}
		}
		
		if($agentId) {
			$agent = AgentShop::get($agentId);
			return $agent ? $agent['user_id'] : '';
		}
		
		return '';
	}
}